﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Caching;
using System.Text;
using System.Threading.Tasks;

namespace Core.Configuration.Helper
{
    public class CacheHelper
    {
        static MemoryCache cache = new MemoryCache("defaultCache");
        public static void Add(string key, object value, int secends)
        {
            cache.Set(key, value, new DateTimeOffset(DateTime.Now.AddSeconds(secends)));
        }

        /// <summary>
        /// 获取本地缓存
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string Get(string key)
        {
            var obj = cache.Get(key);
            return obj != null ? obj.ToString() : string.Empty;
        }

        /// <summary>
        /// 获取本地缓存
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key"></param>
        /// <returns></returns>
        public static T Get<T>(string key)
        {
            var obj = cache.Get(key);
            return obj != null ? (T)obj : default(T);
        }

        /// <summary>
        /// 获取本地缓存,没有则添加
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key"></param>
        /// <param name="value"></param>
        /// <param name="secends">缓存多少秒</param>
        /// <returns></returns>
        public static T GetAdd<T>(string key, object value, int secends) where T : class, new()
        {
            var obj = cache.Get(key);
            if (obj == null)
            {
                cache.Set(key, value, new DateTimeOffset(DateTime.Now.AddSeconds(secends)));
            }
            return obj != null ? (T)obj : default(T);
        }
    }
}
